$(function() {
    $("body").i18n();
    $("#bodyLayOut").layout('panel', 'west').panel('setTitle', $.i18n.get('sample2.tree.label'));
    function onTreeSelect(node) {
        $("#search_devOrgName").val(node.text);
        $("#search_devOrgId").val(node.id);
        onSearch();
    }
    $("#devOrgTree").tree({
        animate : true,
        checkbox : false,
        type : "post",
        treeRoot : "devOrgs",
        url : contextPath + "/sample/loadDevOrgRoots.pvt",
        onSelect : onTreeSelect
    });
    
    $("#search_peopleId").combogrid({
        panelWidth : 450,
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : true,
        totalProperty : "total",
        rowsProperty : "peoples",
        url : contextPath + '/sample/findPageByPeople.pvt',
        idField : 'id',
        textField : 'name',
        mode : 'remote',
        columns : [[{
            field : 'name',
            width : 240,
            title : $.i18n.get('people.name')
        }, {
            field : 'age',
            align : 'center',
            width : 140,
            title : $.i18n.get('people.age')
        }]],
        onBeforeLoad : function(param) {
            param.name = param.q;
            delete param.q;
            return true;
        }
    });
    $("#edit_peopleId").combobox({
        url : contextPath + '/sample/findPeoples.pvt',
        valueField : 'id',
        textField : 'name',
        panelHeight : 'auto',
        multiple : false,
        editable : false
    });
    var levelData = [{
        key : '',
        value : $.i18n.get('level.all')
    }, {
        key : 1,
        value : $.i18n.get('level.primary')
    }, {
        key : 2,
        value : $.i18n.get('level.junior')
    }, {
        key : 3,
        value : $.i18n.get('level.senior')
    }, {
        key : 4,
        value : $.i18n.get('level.expert')
    }];
    
    // 带checkbox的多选框
    $("#search_levelTo").combobox({
        valueField : 'key',
        textField : 'value',
        panelHeight : 'auto',
        multiple : true,
        editable : false,
        data : levelData,
        formatter : function(row) {
            var opts = $(this).combobox('options');
            return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
        },
        onLoadSuccess : function() {
            var opts = $(this).combobox('options');
            var target = this;
            var values = $(target).combobox('getValues');
            $.map(values, function(value) {
                var el = opts.finder.getEl(target, value);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            })
        },
        onSelect : function(row) {
            var opts = $(this).combobox('options');
            var el = opts.finder.getEl(this, row[opts.valueField]);
            el.find('input.combobox-checkbox')._propAttr('checked', true);
            var checkedValAry = $(this).combobox('getValues');
            if (row.key === '') {
                $(this).combobox('setValue', '');
                for ( var ckVal in checkedValAry) {
                    if (checkedValAry[ckVal] !== '') {
                        var el2 = opts.finder.getEl(this, checkedValAry[ckVal]);
                        el2.find('input.combobox-checkbox')._propAttr('checked', false);
                    }
                }
            } else {
                var hasAllSelect = false;
                for ( var ckVal in checkedValAry) {
                    if (checkedValAry[ckVal] === '') {
                        checkedValAry.splice(ckVal, 1);
                        hasAllSelect = true;
                        break;
                    }
                }
                if (hasAllSelect) {
                    var el2 = opts.finder.getEl(this, '');
                    el2.find('input.combobox-checkbox')._propAttr('checked', false);
                    $(this).combobox('setValues', checkedValAry);
                }
            }
        },
        onUnselect : function(row) {
            var opts = $(this).combobox('options');
            var el = opts.finder.getEl(this, row[opts.valueField]);
            el.find('input.combobox-checkbox')._propAttr('checked', false);
        }
    });
    $("#edit_levelTo").combobox({
        valueField : 'key',
        textField : 'value',
        panelHeight : 'auto',
        multiple : false,
        editable : false,
        data : [{
            key : '',
            value : $.i18n.get('emptyText')
        }, {
            key : 1,
            value : $.i18n.get('level.primary')
        }, {
            key : 2,
            value : $.i18n.get('level.junior')
        }, {
            key : 3,
            value : $.i18n.get('level.senior')
        }, {
            key : 4,
            value : $.i18n.get('level.expert')
        }]
    });
    
    $('#devBonusGrid').datagrid({
        toolbar : '#datagrid-toolbar',
        url : contextPath + '/sample/findPageByDevBonus.pvt',
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : false,
        idField : 'id',
        nowrap : false,
        pagePosition : 'top',
        totalProperty : "total",
        rowsProperty : "devBonuses",
        frozenColumns : [[{
            field : 'id',
            checkbox : true
        }]],
        columns : [[{
            field : 'devOrgName',
            width : 140,
            title : $.i18n.get('devBonus.devOrg')
        }, {
            field : 'people',
            align : 'center',
            width : 140,
            title : $.i18n.get('devBonus.people'),
            formatter : function(value, row, index) {
                return value == null ? '' : value.name;
            }
        }, {
            field : 'money',
            align : 'center',
            width : 120,
            title : $.i18n.get('devBonus.money')
        }, {
            field : 'levelTo',
            align : 'center',
            width : 100,
            title : $.i18n.get('devBonus.levelTo'),
            formatter : function(value, row, index) {
                if (value == null) {
                    return '';
                }
                for (var i = 1; i < levelData.length; i++) {
                    if (levelData[i].key == value) {
                        return levelData[i].value;
                    }
                }
                return "";
            }
        }]],
        onBeforeLoad : function(param) {
            if (!$("#queryForm").form('validate')) {
                return false;
            }
            $.extend(param, $('#queryForm').serializeJson());
            if ($.isArray(param.levelTo)) {
                param.levelTo = param.levelTo.join(",");
            }
            return true;
        }
    });
    window.onSearch = function() {
        $('#devBonusGrid').datagrid('clearSelections').datagrid('load', {})
    }
    window.onSearchReset = function() {
        $('#queryForm').form('reset');
        $("#search_devOrgId").removeAttr('value');
    }
    
    $("#devBonusDialog").dialog({
        closed : true
    });

    window.onAdd = function() {
        if ($("#search_devOrgId").val() == '') {
            showPromptMsg($.i18n.get('sample2.tree.select'));
            return;
        }
        window.isEditing = false;
        $("#devBonusDialog").dialog({
            title : $.i18n.get('add')
        }).dialog('open');
        onReset();
    }

    window.onEdit = function() {
        var selectedRow = getSelectedRow('#devBonusGrid');
        if (selectedRow) {
            doEdit(selectedRow);
        }
    }
    
    function doEdit(selectedRow) {
        window.isEditing = true;
        window.editRow = selectedRow;
        $("#devBonusDialog").dialog({
            title : $.i18n.get('edit')
        }).dialog('open');
        onReset();
    }
    
    window.onReset = function() {
        $('#devBonusForm').form('reset');
        $('#edit_devOrgName').val($('#search_devOrgName').val());
        if (window.isEditing && window.editRow != undefined && window.editRow != null) {
            var formData = $.extend({}, window.editRow);
            formData.award1 = formData.award1 == true ? 'on' : 'off';
            formData.award2 = formData.award2 == true ? 'on' : 'off';
            formData.award3 = formData.award3 == true ? 'on' : 'off';
            $('#devBonusForm').form('load', formData);
        } else {
            $('#devBonusForm').form('load', {
                money : 10000,
                levelTo : null,
                award1 : 'off',
                award2 : 'off',
                award3 : 'off',
                note : null
            });
        }
    }
    
    window.onDel = function() {
        var selectedRow = getSelectedRow('#devBonusGrid', true);
        if (selectedRow) {
            $.messager.confirm($.i18n.get('prompt'), $.i18n.get('confirmDeleteData'), function(result) {
                if (result) {
                    var ids = [];
                    $(selectedRow).each(function() {
                        ids.push(this.id);
                    });
                    $.messager.progress({
                        title : $.i18n.get('prompt'),
                        msg : $.i18n.get('waitingMessage')
                    });
                    $.ajax({
                        url : contextPath + '/sample/deleteDevBonuses.pvt',
                        data : {
                            ids : ids.join(",")
                        },
                        type : "post",
                        success : function(resp) {
                            $.messager.progress('close');
                            if (resp.success == true) {
                                onSearch();
                            } else {
                                $.messager.alert($.i18n.get('error'), resp.msg, 'error');
                            }
                        },
                        error : function(xhr, status, error) {
                            $.messager.progress('close');
                            $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
                        }
                    });
                }
            });
        }
    }
    
    window.onSave = function() {
        if ($("#devBonusForm").form("validate")) {
            var devBonus = $("#devBonusForm").serializeJson();
            devBonus.award1 = devBonus.award1 == 'on';
            devBonus.award2 = devBonus.award2 == 'on';
            devBonus.award3 = devBonus.award3 == 'on';
            if (window.isEditing) {
                devBonus.id = window.editRow.id;
                devBonus.devOrgId = window.editRow.devOrgId;
            } else {
                devBonus.devOrgId = $("#search_devOrgId").val();
            }
            doSave({
                devBonus : devBonus
            });
            return false;
        }
        return false;
    }
    
    function doSave(paramData) {
        $.messager.progress({
            title : $.i18n.get('prompt'),
            msg : $.i18n.get('waitingMessage')
        });
        $.ajax({
            type : 'post',
            url : contextPath + "/sample/saveDevBonus.pvt",
            data : JSON.stringify(paramData),
            contentType : 'application/json; charset=UTF-8',
            processData : false,
            dataType : 'json',
            success : function(resp, status, xhr) {
                $.messager.progress('close');
                if (resp.success) {
                    $("#devBonusDialog").dialog('close');
                    $.messager.alert($.i18n.get('prompt'), $.i18n.get('saveSuccess'), 'info', function(){
                        onSearch();
                    });
                } else {
                    $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.exception"), 'error');
                }
            },
            error : function(xhr, status, error) {
                $.messager.progress('close');
                $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
            }
        });
    }
    
    function getSelectedRow(selector, multiple) {
        var selectedRows = $(selector).datagrid('getSelections');
        if (selectedRows.length == 0) {
            showPromptMsg($.i18n.get('selectMinOneRecord'));
            return false;
        } else if (!multiple && selectedRows.length > 1) {
            showPromptMsg($.i18n.get('selectOneRecord'));
            return false;
        } else {
            return multiple ? selectedRows : selectedRows[0];
        }
    }
    
    function showPromptMsg(msg) {
        $.messager.alert($.i18n.get('prompt'), msg, 'warning');
    }
});